package com.weigj.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.weigj.model.CarInfo;
import com.weigj.model.Content;
import com.weigj.model.Dept;
import com.weigj.model.Employee;
import com.weigj.model.HourContract;
import com.weigj.model.HourContractBackSett;
import com.weigj.model.OtherMoneyInfo;
import com.weigj.model.PayInfo;
import com.weigj.model.ReserveHour;
import com.weigj.service.DeptAppService;

public class DeptAppServiceImpl implements DeptAppService {

	public Employee loginSuccess(String loginName, String password)
	{
		Employee id = null;
		String sql = "select * from app_caremployee e where e.empllogin=? and e.emplpwd=?";
		id = Employee.dao.findFirst(sql, loginName, password);
		return id;
	}
	public Content checkReserveHourContractCarCanRent(String carMakeCode, String num)
	{
		String code="000";
		String msg="";
		Content c = new Content();
		try
		{
			Preconditions.checkArgument(!Strings.isNullOrEmpty(carMakeCode));
			Preconditions.checkArgument(!Strings.isNullOrEmpty(num));
		} catch (Exception e)
		{
			c.setCode("111");
			c.setMsg("条件不完整,请重试");
		}
		CarInfo qrCar = null;
		CarInfo reserveCar = null;
		qrCar = CarInfo.dao.queryCarInfo(carMakeCode);
		System.out.println(num);
		reserveCar=ReserveHour.dao.queryCarInfoByNum(num);
		if(reserveCar!=null&&qrCar!=null){
			if(qrCar.getBigDecimal("INFOID").longValue()==reserveCar.getBigDecimal("INFOID").longValue()){
				return c;
			}
			if(qrCar.getBigDecimal("INFOID")!=reserveCar.getBigDecimal("INFOID")){
				long qrMode=qrCar.getBigDecimal("TOPCARMODELID").longValue();
				long resCarMode=reserveCar.getBigDecimal("TOPCARMODELID").longValue();
				String qrCarState = qrCar.getStr("carstate");
				if(qrCarState.equals("待租")&&qrMode==resCarMode){
					msg = "当前车辆车牌号与订单车辆车牌号不符,当前车辆为待租,可执行换车发车操作";
					code = "001";
				}else{
					msg = "当前车辆车牌号与订单车辆车牌号不符,当前车辆为非待租状态或车辆型号不一致,请重新扫描车辆";
					code = "100";
				}
			}
		}else{
			msg="系统找不到该车辆，请查证该车辆是否在系统中";
			code="404";
		}
		c.setCode(code);
		c.setMsg(msg);
		return c;
	}


	public String queryUserDeptFunc(String userId)
	{
		List<Dept> uds = new ArrayList<Dept>();
		String sql = "select distinct(ad.deptfunc) from app_cardept ad where ad.deptfunc like '区域站点%' and ad.DEPTID in (select aud.dept_id from app_user_dept aud where aud.dept_emp_id=?)";
		uds = Dept.deptDao.find(sql,userId);
		System.out.println(uds.size());
		StringBuffer json = new StringBuffer();
		json.append("{");
		json.append("\"deptFunc\"").append(":[");
		for(int i=0;i<uds.size();i++)
		{
			json.append("\"").append(uds.get(i).getStr("deptfunc")).append("\"");
			if(i<uds.size()-1){
				json.append(",");
			}
		}
		json.append("]}");
		return json.toString(); 
	}

	public List<Dept> queryUserDepts(String deptFunc,String empId)
	{
		List<Dept> depts = new ArrayList<Dept>();
		StringBuffer json = new StringBuffer();
		String sql = "select * from app_cardept dept where dept.deptfunc=? and dept.deptid in (select aud.dept_id from app_user_dept aud where aud.dept_emp_id=?)";
		depts= Dept.deptDao.find(sql,deptFunc,empId);
		return depts;
	}

	public List<ReserveHour> queryOrderList(String deptId)
	{
		List<ReserveHour> list = new ArrayList<ReserveHour>();
		try
		{
			Preconditions.checkArgument(!Strings.isNullOrEmpty(deptId));
		} catch (Exception e)
		{
			System.out.println("deptid为空");
			return null;
		}
		String sql = "select * from APP_RESERVEHOUR t where t.carlocalid=? and t.reserveState=1 order by id desc";
		list = ReserveHour.dao.find(sql,deptId);
		return list;
	}

	public ReserveHour queryOneOrderById(String orderId)
	{
		ReserveHour rh = new ReserveHour();
		try
		{
			Preconditions.checkArgument(!Strings.isNullOrEmpty(orderId));
		} catch (Exception e)
		{
			System.out.println(" orderId is null");
			return null;
		}
		rh = ReserveHour.dao.findById(orderId);
		return rh;
	}

	public List<ReserveHour> queryOrderByNum(String orderNum,String localId)
	{
		List<ReserveHour> rhs = null;
		try
		{
			Preconditions.checkArgument(!Strings.isNullOrEmpty(orderNum));
			Preconditions.checkArgument(!Strings.isNullOrEmpty(localId));
		} catch (Exception e)
		{
			System.out.println("订单号或登录部门为空");
			return null;
		}
		String sql = "select * from APP_RESERVEHOUR t where t.reserveNo like \'%"+orderNum.trim()+"\' and t.carLocalId="+localId;
		rhs = ReserveHour.dao.find(sql);
		return rhs;
	}

	public CarInfo queryCarInfo(String param)
	{
		return CarInfo.dao.queryCarInfo(param);
	}


	public boolean sendCar(String initKM, String orderId, String carInfoLicense,String inputer)
	{
		
		String result = "";// 返回的结果   
        BufferedReader in = null;// 读取响应输入流   
        PrintWriter out = null;   
        StringBuffer sb = new StringBuffer();// 处理请求参数   
        String params = "";// 编码之后的参数
		try {
			//准备参数
			sb.append("initKM=").append(initKM);
			sb.append("&flag=").append("sendCar");
			sb.append("&orderId=").append(orderId);
			sb.append("&inputer=").append(URLEncoder.encode(inputer,"UTF-8"));
			sb.append("&carInfoLicense=").append(URLEncoder.encode(carInfoLicense,"UTF-8"));
			params=sb.toString();
			String url="http://localhost:8080/WGJACT/servlet/ReserveConvertHtServlet";
			java.net.URL connURL = new java.net.URL(url);
			// 打开URL连接
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);   
            httpConn.setDoOutput(true);   
            // 获取HttpURLConnection对象对应的输出流   
            out = new PrintWriter(httpConn.getOutputStream());   
            // 发送请求参数   
            out.write(params);   
			// 获取HttpURLConnection对象对应的输出流
			//out = new PrintWriter(httpConn.getOutputStream());
			out.flush();   
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式   
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GBK"));   
            String line;   
            // 读取返回的内容   
            while ((line = in.readLine()) != null) {   
                result += line;   
            }
            if(result.equals("success")){
            	  return true;
            }else if(result.equals("error")){
            	 return false;
            }
         
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{   
                if (out != null) {   
                    out.close();   
                }   
                if (in != null) {   
                    in.close();   
                }   
            } catch (IOException ex) {   
                ex.printStackTrace();   
            }   
		}
		return false;
	}


	public List<CarInfo> queryCarListCanRent(String deptId)
	{
		List<CarInfo> cars = new ArrayList<CarInfo>();
		String sql = "select * from APP_CARINFO c where c.carstate =? and c.localid=?";
		cars = CarInfo.dao.find(sql,"待租",deptId);
		return cars;
	}

	public Object queryContractByCarLicense(String carInfoLicense)
	{
		// TODO Auto-generated method stub
		return null;
	}

	public boolean backCarSuccess(String backCarFlag,String hourContractId, String backDate, String endKM,String deptId,String empName)
	{
		String result = "";// 返回的结果   
        BufferedReader in = null;// 读取响应输入流   
        PrintWriter out = null;   
        StringBuffer sb = new StringBuffer();// 处理请求参数   
        String params = "";// 编码之后的参数
		try {
			//准备参数
			sb.append("hourContractId=").append(hourContractId);
			sb.append("&flag=").append("backCar");
			sb.append("&backCarFlag=").append(backCarFlag);
			sb.append("&backDate=").append(backDate);
			sb.append("&endKM=").append(endKM);
			sb.append("&inputer=").append(URLEncoder.encode(empName,"utf-8"));
			sb.append("&deptId=").append(deptId);
			params=sb.toString();
			String url="http://localhost:8080/WGJACT/servlet/ReserveConvertHtServlet";
			java.net.URL connURL = new java.net.URL(url);
			// 打开URL连接
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);   
            httpConn.setDoOutput(true);   
            // 获取HttpURLConnection对象对应的输出流   
            out = new PrintWriter(httpConn.getOutputStream());   
            // 发送请求参数   
            out.write(params);   
			// 获取HttpURLConnection对象对应的输出流
			//out = new PrintWriter(httpConn.getOutputStream());
			out.flush();   
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式   
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GBK"));   
            String line;   
            // 读取返回的内容   
            while ((line = in.readLine()) != null) {   
                result += line;   
            }
            if(result.equals("success")){
            	  return true;
            }else if(result.equals("error")){
            	 return false;
            }
         
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{   
                if (out != null) {   
                    out.close();   
                }   
                if (in != null) {   
                    in.close();   
                }   
            } catch (IOException ex) {   
                ex.printStackTrace();   
            }   
		}
		return false;
	}

	public Object js(String hourContractId)
	{
		// TODO Auto-generated method stub
		return null;
	}

	public boolean saveJsSuccess(List<OtherMoneyInfo> omiList)
	{
		// TODO Auto-generated method stub
		return false;
	}

	public boolean pay(String payway, String sum)
	{
		// TODO Auto-generated method stub
		return false;
	}

	public List<Object> queryHasBackCarButNotJSContract(String deptId)
	{
		// TODO Auto-generated method stub
		return null;
	}

	public List<Object> queryHasBackCarButNotChangeContract(String deptid)
	{
		// TODO Auto-generated method stub
		return null;
	}

	public boolean queryCarForChange(String param)
	{
		// TODO Auto-generated method stub
		return false;
	}

	public boolean changeCarSuccess(String contractId, String carInfoLicense, String initKM, String deptId,String startTime,String inputer)
	{
		String result = "";// 返回的结果   
        BufferedReader in = null;// 读取响应输入流   
        PrintWriter out = null;   
        StringBuffer sb = new StringBuffer();// 处理请求参数   
        String params = "";// 编码之后的参数
		try {
			//准备参数
			sb.append("hourContractId=").append(URLEncoder.encode(contractId,"UTF-8"));
			sb.append("&flag=").append("changeCarSendCar");
			sb.append("&backDate=").append(startTime);
			sb.append("&km=").append(initKM);
			sb.append("&inputer=").append(URLEncoder.encode(inputer,"utf-8"));
			sb.append("&carNum=").append(URLEncoder.encode(carInfoLicense,"UTF-8"));
			sb.append("&deptId=").append(deptId);
			params=sb.toString();
			String url="http://localhost:8080/WGJACT/servlet/ReserveConvertHtServlet";
			java.net.URL connURL = new java.net.URL(url);
			// 打开URL连接
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);   
            httpConn.setDoOutput(true);   
            // 获取HttpURLConnection对象对应的输出流   
            out = new PrintWriter(httpConn.getOutputStream());   
            // 发送请求参数   
            out.write(params);   
			// 获取HttpURLConnection对象对应的输出流
			//out = new PrintWriter(httpConn.getOutputStream());
			out.flush();   
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式   
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GBK"));   
            String line;   
            // 读取返回的内容   
            while ((line = in.readLine()) != null) {   
                result += line;   
            }
            if(result.equals("success")){
            	  return true;
            }else if(result.equals("error")){
            	 return false;
            }
         
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{   
                if (out != null) {   
                    out.close();   
                }   
                if (in != null) {   
                    in.close();   
                }   
            } catch (IOException ex) {   
                ex.printStackTrace();   
            }   
		}
		return false;
	}
	public boolean successInput(String contractId, String oper, String reason, String money, String shouldInput, String paymethod)
	{
		//更新合同数据 改为已结算
		HourContract.dao.findById(contractId).set("settlement", "1").update();
		PayInfo p =null;
		double dtotalfee=Double.parseDouble(shouldInput);
		if(!Strings.isNullOrEmpty(money)){
			if(oper.equals("增加")){
				money=""+money;
			}else{
				money="-"+money;
			}
			double dmoney = Double.parseDouble(money);
			p=new PayInfo().set("id", "APP_BACKSETTLEMENTFEE_SEQ.nextval").set("payMethod", paymethod).set("payNum",dtotalfee);
			p.save();
			HourContractBackSett.dao.findOneByContractId(contractId).set("payway", paymethod).set("totalFee",dtotalfee).set("otherFee", dmoney).set("note", reason).set("settlementFee_id", p.get("id")).update();
		}else{
			p=new PayInfo().set("id", "APP_BACKSETTLEMENTFEE_SEQ.nextval").set("payMethod", paymethod).set("payNum",dtotalfee);
			p.save();
			HourContractBackSett.dao.findOneByContractId(contractId).set("payway", paymethod).set("settlementFee_id", p.get("id")).update();
		}
		return true;
	}
	public Content checkCanChangeCar(String para){
		Content c = new Content();
		CarInfo car = null;
		car = CarInfo.dao.queryCarInfo(para);
		if(car.getStr("CARSTATE").equals("待租")){
			c.setCode("000");
			c.setC(car);
		}else{
			c.setCode("404");
			c.setMsg("该车非待租状态");
		}
		c.setC(car);
		return c;
	}
}
